#include "wds_ui_helper.h"

#include "input/mouse.h"
#include "ui/ui_widget.h"

void			WDSUIHelper::ResizeToCurentAspectRatio(ui::UIWidget* pWidget)
{
	if(pWidget)
	{
		const float AspectRatioCreated = 720.0f / 1280.0f;
		const float AsepctRatioCurrent = (float)GetGraphics()->GetScreenWidth() / (float)GetGraphics()->GetScreenHeight();
		const float NewHScale =  AsepctRatioCurrent / AspectRatioCreated;	

		// reposition according to screen
		math::Vec2 TempSize = pWidget->GetSize();
		TempSize.y *= NewHScale;
		pWidget->SetSize(TempSize);
		//pWidget->SetPosition( math::Vec2(0.5f, 1.0f - (TempSize.y * 0.5f)) );
	}
}

void		WDSUIHelper::Tick(float dt)
{
	input::Mouse::BUTTON_STATE* pState =
	input::Mouse::Instance().GetButtonState(input::Mouse::BUTTON_LEFT);

	if(!m_pWidget)
		return;

	math::Vec2 MousePos;
	const math::Vec2 Pos = m_pWidget->GetPosition();
	if(pState->ButtonDown  )
		MousePos = input::Mouse::Instance().GetImmediatePos(); 
	else if(pState->IsButtonReleased())
	{
		m_pWidget->SetSize( m_OriginalSize);
		return;
	}

	bool IsInside = true;
	if(m_pWidget )
	{
		if( MousePos.x > Pos.x + (m_OriginalSize.x * 0.5f) ) 
			IsInside = false;
		else if( MousePos.x < Pos.x - (m_OriginalSize.x * 0.5f) ) 
			IsInside = false;
		else if( MousePos.y > Pos.y + (m_OriginalSize.y * 0.5f) ) 
			IsInside = false;
		if( MousePos.y < Pos.y - (m_OriginalSize.y * 0.5f) ) 
			IsInside = false;
	}

	if(IsInside)
	{
		m_pWidget->SetSize( m_OriginalSize * 0.95f);
	}
	else
	{
		m_pWidget->SetSize( m_OriginalSize);
	}
}

WDSUIHelper::WDSUIHelper(ui::UIWidget* pButton)
{
	m_pWidget = NULL;
	if(!pButton)
		return;
	m_pWidget = pButton;
	ResizeToCurentAspectRatio(m_pWidget);
	m_OriginalSize = m_pWidget->GetSize();
		
}

void	WDSUIHelper::RelocateToCurentAspectRatio(ui::UIWidget* pWidget, const math::Vec2& AnchorPoint)
{
	//ResizeToCurentAspectRatio(pWidget);

	const float AspectRatioCreated = 720.0f / 1280.0f;
	const float AsepctRatioCurrent = (float)GetGraphics()->GetScreenWidth() / (float)GetGraphics()->GetScreenHeight();
	const float NewHScale =  AsepctRatioCurrent / AspectRatioCreated;

	math::Vec2 Pos = pWidget->GetPosition();
	float Diff = AnchorPoint.y - Pos.y;
	Diff *= NewHScale;
	Pos.y = AnchorPoint.y - Diff;
	pWidget->SetPosition(Pos);

}